<?php

/**
 * propel object class
 *
 */
class Of_Propel_Object
{
  /**
   * propel object class 
   *
   * @var Of_Propel_IObject $object
   */
  protected $object;
  
  /**
   * constructor
   * 
   * @param Of_Propel_IObject $object
   */
  private function __construct(BaseObject $object)
  {
    $this->object = $object;
  }
  
  /**
   * create new instance
   * 
   * @param BaseObject $object
   * @return Of_Propel_Object
   * 
   */
  public static function newInstance(BaseObject $object)
  {
    return new Of_Propel_Object($object);
  }
  
  /**
   * update or insert record
   * 
   * <code>
   * // if record exists
   * //   update demo_item set document='docs' where name='test'
   * // else
   * //   insert into demo_item(name, document) values('test', 'docs')
   * 
   * $item = new DemoItem();
   * $item->setName("test");
   * $item->setDocument("docs");
   * 
   * Of_Propel_Object::newInstance($item)->replace("Name");
   * 
   * </code>
   * 
   *
   */
  public function replace()
  {
    $class = get_class($this->object);
    $columns = func_get_args();
    $object = new $class;
    
    foreach((array)$columns as $col)
    {
      $object->setByName($col, $this->object->getByName($col));
    }
    
    $rs = $object->getPeer()->doSelectOne($object->buildCriteria());
    $this->object->setNew(true);
    if($rs)
    {
      $this->object->setId($rs->getId());
      $this->object->setNew(false);
    }
    
    return $this->object->save();
    
  }
  
  
  /**
   * Getting one record 
   * 
   * Of_Propel_Object::newInstance(new DemoItem())->retrieveByName("Title", "test");
   *
   * @param string $name
   * @param mixed $key
   * @return BaseObject
   */
  public  function retrieveByName($name, $key, $type = BasePeer::TYPE_PHPNAME)
  {
    $object = $this->object;
    $object->setByName($name, $key, $type);
    return $object->getPeer()->doSelectOne($object->buildCriteria());    
  }  
  
  
}